<template>
  <div>
    <!-- 面包屑导航 -->
    <div class="center-w">
      <div class="head">
        <div class="title">账号管理</div>
        <div class="add">
          <el-button type="success" @click="addAccount">添加账号</el-button>
          <el-input
            @input="inputChange"
            v-model="inputV"
            placeholder="请输入"
            style="width: 200px; "
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
      </div>
      <el-table size="mini" :data="tableData">
        <el-table-column
          width="50px"
          align="center"
          prop="id"
          label="ID"
        ></el-table-column>
        <el-table-column prop="img" align="center" width="300" label="头像">
          <template slot-scope="scope">
            <el-image
              style="width: 40px; height: 40px;"
              :src="scope.row.img"
              fit="cover"
              :lazy="true"
            >
              <div slot="error" class="image-slot">
                <!-- <i class="el-icon-picture-outline"></i> src="https://img1.baidu.com/it/u=4035421571,4160111639&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" -->
                <el-image
                  class="head-img"
                  src="https://img2.baidu.com/it/u=3969906574,3231239394&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500"
                >
                </el-image>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          align="center"
          label="账号名称"
        ></el-table-column>

        <el-table-column prop="isAdmin" align="center" label="账号权限">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdmin"> 普通账号</span>
            <span v-else style="color: #cc3e51;">超级管理员</span>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" align="center" label="状态">
          <template slot-scope="scope">
            <el-switch
              @change="setAuthorityState(scope.row)"
              v-model="scope.row.state"
            ></el-switch>
            <span style="margin-left: 10px;">
              {{ scope.row.state ? "开" : "关" }}
            </span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" width="200px" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="updateAuthority(scope.row.id)"
              >修改账号</el-button
            >
            <el-button
              v-if="!scope.row.isAdmin"
              size="mini"
              type="danger"
              @click="addAuthority(scope.row)"
              >添加权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :title="currentTitle"
      :visible.sync="addAccountDialogVisible"
      width="25%"
      :before-close="closeForm"
    >
      <div class="sex">
        <el-form
          :model="userParams"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名：" prop="userNane">
            <el-input maxlength="8" v-model="userParams.userNane"></el-input>
          </el-form-item>
          <el-form-item label="账号：" prop="userNumber">
            <el-input
              v-model="userParams.userNumber"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="userPassword">
            <el-input
              v-model="userParams.userPassword"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAccountDialogVisible = false">取 消</el-button>
        <!-- <el-button type="info" @click="resetForm('ruleForm')">重 置</el-button> -->
        <el-button type="primary" @click="addUserNumber('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 权限详情 -->
    <el-dialog title="权限详情" :visible.sync="infoVisible" width="35%">
      <el-collapse v-model="activeNames">
        <el-collapse-item title="注意事项" name="1">
          <div>
            路由权限是控制用户是否有权限访问左侧的tab栏。<span
              style="color: #cc3e51;"
              >(路由权限大于二级菜单权限和按钮权限)！</span
            >
          </div>
          <div>
            如需设置
            <span style="color: #cc3e51;">(订单管理,用户管理,充值管理)</span>
            的按钮权限和二级菜单权限时, 必须先设置用户的路由权限才能生效！
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-tree
        :data="dataList"
        show-checkbox
        :default-expanded-keys="[1, 3]"
        node-key="id"
        ref="tree"
        highlight-current
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="infoVisible = false">取 消</el-button>
        <el-popconfirm
          confirm-button-text="确定"
          cancel-button-text="取消"
          icon="el-icon-info"
          icon-color="red"
          title="确定给该用户这些权限吗？"
          @confirm="submitAuthority"
        >
          <el-button slot="reference" type="primary">提 交</el-button>
        </el-popconfirm>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAccountPageList,
  addAccountNumber,
  updateAccountNumber,
  getAccountId
} from "../../api/permission";
export default {
  data() {
    //验证用户名
    let checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else {
        callback();
      }
    };
    //验证账号
    let checkTel = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("账号不能为空"));
      } else {
        const reg = /^[_a-zA-Z0-9]+$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(
            new Error("账号仅由12位英文字母，数字以及下划线组成")
          );
        }
      }
    };
    //验证密码
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        const reg = /^[_a-zA-Z0-9]+$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(
            new Error("密码仅由12位英文字母，数字以及下划线组成")
          );
        }
      }
    };
    return {
      //搜索框
      inputV: "",
      // 目前没有做列表处理 后续需要多功能控制在进行优化处理
      tableData: [],
      activeNames: ["1"],
      rules: {
        userPassword: [
          { validator: validatePass, trigger: "blur" },
          {
            pattern: /^(\w){6,12}$/,
            message: "只能输入6-12个字母、数字、下划线"
          }
        ],
        userNumber: [
          { validator: checkTel, trigger: "blur" },
          {
            pattern: /^(\w){6,12}$/,
            message: "只能输入6-12个字母、数字、下划线"
          }
        ],
        userNane: [{ validator: checkUserName, trigger: "blur" }]
      },

      // 账号数据
      userParams: {
        userNane: "",
        userNumber: "",
        userPassword: ""
      },
      // 账号input框禁用
      disabled: false,
      id: "",
      addAccountDialogVisible: false,
      infoVisible: false,
      currentTitle: "",
      checkAll: false,
      checkedCities: [],
      //权限数据列表
      dataList: [
        {
          id: 1,
          label: "路由权限",
          children: [
            {
              id: "OrderManagement",
              label: "订单管理"
            },
            {
              id: "UserManagement",
              label: "用户管理"
            },
            {
              id: "RechargeManagement",
              label: "充值管理"
            },
            {
              id: "RefundManagement",
              label: "退款管理"
            },
            {
              id: "CouponManagement",
              label: "优惠券管理"
            },
            {
              id: "IdentityManagement",
              label: "身份管理"
            },
            {
              id: "ArticleManagement",
              label: "文章管理"
            },
            {
              id: "ReportCenter",
              label: "统计中心"
            },
            {
              id: "CommodityManagement",
              label: "商品管理"
            },
            {
              id: "PageManagement",
              label: "首页管理"
            },
            {
              id: "DistributionManagement",
              label: "分销管理"
            },
            {
              id: "GiftManagement",
              label: "礼包管理"
            },
            {
              id: "MettingManagement",
              label: "会议室管理"
            },
            {
              id: "SignActivityManagement",
              label: "签到活动"
            }
          ]
        },
        {
          id: 2,
          label: "用户管理二级菜单权限",
          children: [
            {
              id: "UserList",
              label: "用户列表"
            },
            {
              id: 3,
              label: "用户列表按钮权限",
              children: [
                {
                  id: "SetUser",
                  label: "用户编辑"
                },
                {
                  id: "SetControl",
                  label: "后台控制"
                },
                {
                  id: "SetIdentity",
                  label: "设置身份"
                }
              ]
            },
            {
              id: "LabelManagement",
              label: "标签管理"
            },
            {
              id: "CompanyManagement",
              label: "公司管理"
            }
          ]
        },
        {
          id: 4,
          label: "订单管理按钮权限",
          children: [
            {
              id: "ExportOrder",
              label: "导出订单"
            },
            {
              id: "Confirm",
              label: "验货确认"
            },
            {
              id: "UpdateOrder",
              label: "编辑订单"
            },
            {
              id: "SendMsg",
              label: "发送评论"
            },
            {
              id: "DeleteMsg",
              label: "删除评论"
            },
            {
              id: "MonthlyOrder",
              label: "月结订单"
            },
            {
              id: "MonthlyCount",
              label: "月结计算/结清"
            },
            {
              id: "OrderRefund",
              label: "退款"
            }
          ]
        },
        {
          id: 5,
          label: "充值管理二级菜单权限",
          children: [
            {
              id: "SetRecharge",
              label: "充值设置"
            },
            {
              id: "RechargeList",
              label: "充值列表"
            }
          ]
        },
        {
          id: 6,
          label: "商品管理二级菜单权限",
          children: [
            {
              id: "CommodityList",
              label: "商品管理"
            },
            {
              id: "BrandManagement",
              label: "品牌管理"
            },
            {
              id: "ProducerManagement",
              label: "产地管理"
            },
            {
              id: "PackageManagement",
              label: "封装管理"
            }
          ]
        },
        {
          id: 7,
          label: "签到活动二级菜单权限",
          children: [
            {
              id: "SignList",
              label: "签到管理"
            },
            {
              id: "ActivityList",
              label: "活动管理"
            }
          ]
        }
      ],
      isIndeterminate: true
    };
  },

  created() {
    this._getAccountPageList({
      size: 100,
      pageindex: 1
    });
  },
  methods: {
    // 查询
    inputChange(v) {
      this._getAccountPageList({
        size: 100,
        pageindex: 1,
        name: v
      });
    },

    // 获取权限列表
    async _getAccountPageList(params) {
      let res = await getAccountPageList(params);
      if (res.data) {
        this.tableData = res.data.items;
      } else {
        this.tableData = [];
      }
    },

    // 新增账号
    async _addAccount(data) {
      let res = await addAccountNumber(data);
      if (res.data == true) {
        this.addAccountDialogVisible = false;
        this._getAccountPageList({
          size: 100,
          pageindex: 1
        });
      }
    },

    // 修改账号
    async _updateAccount(data) {
      let res = await updateAccountNumber(data);
      if (res.data == true) {
        this.addAccountDialogVisible = false;
        this._getAccountPageList({
          size: 100,
          pageindex: 1
        });
      }
    },

    // 根据id获取信息
    async _getAccountId(params) {
      let res = await getAccountId(params);
      this.userParams = {
        userNane: res.data.userName,
        userNumber: res.data.account,
        userPassword: res.data.passWord
      };
      if (this.infoVisible) this.$refs.tree.setCheckedKeys(res.data.auth); // 回显
    },

    // 关闭弹出层时去校验
    closeForm(done) {
      this.userParams = {
        userNane: "",
        userNumber: "",
        userPassword: ""
      };
      this.resetForm("ruleForm");
      done();
    },

    // 添加权限
    addAuthority(c) {
      this.id = c.id;
      this._getAccountId({ id: c.id });
      this.infoVisible = true;
    },

    //确认添加账号
    addUserNumber(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          if (this.currentTitle == "添加账号") {
            this._addAccount({
              userName: this.userParams.userNane,
              account: this.userParams.userNumber,
              passWord: this.userParams.userPassword
            });
          } else {
            this._updateAccount({
              id: this.id,
              userName: this.userParams.userNane,
              account: this.userParams.userNumber,
              passWord: this.userParams.userPassword
            });
          }
        } else {
          return false;
        }
      });
    },

    //提交用户权限
    submitAuthority() {
      let auth = this.getCheckedKeys();
      this._updateAccount({
        id: this.id,
        auth
      });
      this.infoVisible = false;
    },

    // 获取点击的所以权限
    getCheckedKeys() {
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      const thirdNodeIds = [];
      for (let i = 0; i < checkedKeys.length; i++) {
        const nodeData = this.$refs.tree.getNode(checkedKeys[i]);
        // 获取所有的节点id信息 也可以获取其他的看nodeData的信息
        thirdNodeIds.push(nodeData.data.id);
      }
      // 打印所有选中的第三级节点的 id 集合
      let ids = thirdNodeIds.filter(v => {
        return typeof v != "number";
      });
      return ids;
    },

    //重置
    resetForm(ruleForm) {
      this.$refs[ruleForm].resetFields();
    },

    // 修改账号
    updateAuthority(id) {
      this.id = id;
      this._getAccountId({ id });
      this.addAccountDialogVisible = true;
      this.disabled = true;
      this.currentTitle = "修改账号";
    },

    //添加账号
    addAccount() {
      this.userParams = {
        userNane: "",
        userNumber: "",
        userPassword: ""
      };
      this.addAccountDialogVisible = true;
      this.disabled = false;
      this.currentTitle = "添加账号";
    },

    //设置账号的权限状态
    setAuthorityState(c) {
      this.id = c.id;
      this.$confirm(`确定${c.state ? "打开" : "关闭"}吗？`, "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          this._updateAccount({
            id: this.id,
            state: c.state
          });
        })
        .catch(action => {
          c.state = !c.state;
          this.$message.info("已取消");
        });
    }
  }
};
</script>

<style lang="less" scoped>
.center-w {
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  background-color: #fff;
  height: 85vh;
  padding: 20px;
  border: 1px solid #ccc;
  margin: 20px;
  .title {
    color: rgba(16, 16, 16, 1);
    font-size: 20px;
    margin-bottom: 10px;
  }
  .add {
    .el-input {
      margin-left: 20px;
    }
  }
  .head {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.sex {
  .sex div {
    margin-bottom: 10px;
    padding: 0 30px;
  }
  .sex div span {
    display: inline-block;
    width: 60px;
    font-weight: 700;
  }
  .el-input {
    max-width: 300px;
  }
}
</style>
